package com.pudu.pudusclient;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.DataProcess.UWBDataProcess;
import com.decode.Coding;
import com.decode.Decode;
import com.pudu.myformat.MyFormat;
import com.pudu.pdrobot.App;
import com.pudutech.pdrobot.R;

import java.util.Arrays;


public class ClientAct extends Activity{

	EditText edServerIP;
	Button mBtnControl;
	private boolean bConnected = false;
	public ControlClientService myclientService;


	//control panel
	private TextView tvReceiveShow;
	private TextView tvDefaultSetting;
	private TextView tvSetSpeed;
	private TextView tvSetDir;

	private TextView tvSpeedShow;
	private TextView tvUWBShow;
	private TextView tvIRDShow;
	private TextView tvStatusShow;
	private TextView tvSenersShow;

	private Button btnStop;
	private Button btnAutomatic;

	private RadioButton rbBack2Zero;
	private RadioButton rbCloseLoop;

	private VerticalSeekBar sbSetSpeed;
	private SeekBar sbSetDir;

	private int speedRange = 100;
	private int speedZero = speedRange/2;
	private int dirRange = 60;
	private int dirZero = dirRange/2;

	private int timer = 0;
	private boolean isDebug = false;
	private boolean isEnable = false;
	private boolean isAutomatic = false;
	private boolean isReturn = false;
	private boolean isRefresh = false;

	private boolean isCloseLoop = true;
	private boolean isBack2Zero = true;

	private int setCenter = 0;   //设置的是中心速度
	private int setDir = 0;      //设置的是左右轮速度差

	private EditText etKp;
	private EditText etKi;
	private EditText etKd;
	private EditText etParameter1;
	private EditText etParameter2;
	private Button btnSetPid;
	private Button btnRefresh;
	int kp = 200;
	int ki = 180;
	int kd = 0;
	int optimizeK = 0;
	int optimizeValue = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.debug_activity_client);

		edServerIP = (EditText)this.findViewById(R.id.etClient);
		mBtnControl = (Button)this.findViewById(R.id.btsend);

		edServerIP.setInputType(EditorInfo.TYPE_CLASS_PHONE);

		//enable when service connected
		mBtnControl.setEnabled(false);
		StartService();
		initUI();
		//control panel
		initView();

		//initTimer();
		tvDefaultSetting.setText(String.format("默认设置：Kp%d, Ki%d, Kd%d",kp,ki,kd));
	}

	private void initView(){

		tvSetSpeed = (TextView) findViewById(R.id.tvSetSpeed );
		tvSetDir = (TextView) findViewById(R.id.tvSetDir);
		tvReceiveShow = (TextView) findViewById(R.id.tvReceiveShow);
		tvDefaultSetting = (TextView) findViewById(R.id.tvDefaultSetting);
		tvSpeedShow = (TextView) findViewById(R.id.tvSPDShow);
		tvUWBShow = (TextView) findViewById(R.id.tvUWBShow);
		tvIRDShow = (TextView) findViewById(R.id.tvIRDShow);
		tvStatusShow = (TextView) findViewById(R.id.tvStatusShow);
		tvStatusShow.setMovementMethod(ScrollingMovementMethod.getInstance());
		tvSenersShow = (TextView)findViewById(R.id.tvSensersShow);
     	tvSenersShow.setMovementMethod(ScrollingMovementMethod.getInstance());

		sbSetSpeed = (VerticalSeekBar) findViewById(R.id.sbSetSpeed);
		sbSetDir = (SeekBar) findViewById(R.id.sbSetDir);

		rbBack2Zero = (RadioButton) findViewById(R.id.rbBackToZero);
		rbBack2Zero.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (isBack2Zero) {
					isBack2Zero = false;
					rbBack2Zero.setChecked(false);
				} else {
					isBack2Zero = true;
					rbBack2Zero.setChecked(true);
					sbSetSpeed.setProgress(speedZero);
					sbSetDir.setProgress(dirZero);
				}
			}
		});
		rbCloseLoop = (RadioButton) findViewById(R.id.rbCloseLoop);
		rbCloseLoop.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (isCloseLoop) {
					isCloseLoop = false;
					rbCloseLoop.setChecked(false);
					myclientService.SendCMD(sendData.flag(isDebug,isEnable,isAutomatic,isReturn,isCloseLoop));
				} else {
					isCloseLoop = true;
					rbCloseLoop.setChecked(true);
					myclientService.SendCMD(sendData.flag(isDebug,isEnable,isAutomatic,isReturn,isCloseLoop));
				}
			}
		});

		etParameter1 = (EditText) findViewById(R.id.etParameter1);
		etParameter2 = (EditText) findViewById(R.id.etParameter2);
		etKp = (EditText) findViewById(R.id.etKp);
		etKi = (EditText) findViewById(R.id.etKi);
		etKd = (EditText) findViewById(R.id.etKd);

		btnRefresh = (Button) findViewById(R.id.btRefresh);
		btnRefresh.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				isRefresh = true;
				myclientService.SendCMD(sendData.flag(isDebug,isEnable,isAutomatic,isReturn,isCloseLoop,isRefresh));
				isRefresh = false;
			}
		});

		btnSetPid = (Button) findViewById(R.id.btnSetPid);
		btnSetPid.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String str;
				str = etKp.getText().toString();
				if(!str.equals(""))
					kp = Integer.parseInt(str);

				str = etKi.getText().toString();
				if(!str.equals(""))
					ki = Integer.parseInt(str);

				str = etKd.getText().toString();
				if(!str.equals(""))
					kd = Integer.parseInt(str);

				str = etParameter1.getText().toString();
				if(!str.equals(""))
					optimizeK = Integer.parseInt(str);

				str = etParameter2.getText().toString();
				if(!str.equals(""))
					optimizeValue = Integer.parseInt(str);

				myclientService.SendCMD(sendData.PID((short) kp,(short)ki,(short)kd));
				myclientService.SendCMD(sendData.optimize((short) optimizeK,(short) optimizeValue));
			}
		});

		btnStop = (Button) findViewById(R.id.btnStop);
		btnStop.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (isEnable) {
					isEnable = false;
					btnStop.setText("启动");
					sbSetDir.setProgress(dirZero);
					sbSetSpeed.setProgress(speedZero);
					myclientService.SendCMD(sendData.flag(isDebug,isEnable,isAutomatic,isReturn,isCloseLoop));
				} else {
					isEnable = true;
					btnStop.setText("停车");
					myclientService.SendCMD(sendData.flag(isDebug,isEnable,isAutomatic,isReturn,isCloseLoop));
				}
			}
		});

		btnAutomatic = (Button) findViewById(R.id.btnAutomatic);
		btnAutomatic.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (isAutomatic) {
					isAutomatic = false;
					btnAutomatic.setText("巡线");
					myclientService.SendCMD(sendData.flag(isDebug,isEnable,isAutomatic,isReturn,isCloseLoop));
				} else {
					isAutomatic = true;
					btnAutomatic.setText("遥控");
					myclientService.SendCMD(sendData.flag(isDebug,isEnable,isAutomatic,isReturn,isCloseLoop));
				}
			}
		});

		sbSetSpeed.setMax(speedRange);
		sbSetSpeed.setProgress(speedZero);
		sbSetSpeed.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			@Override
			public void onStopTrackingTouch(SeekBar arg0) {
				// TODO Auto-generated method stub
				if(isBack2Zero)
					sbSetSpeed.setProgress(speedZero);
			}

			@Override
			public void onStartTrackingTouch(SeekBar arg0) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
				// TODO Auto-generated method stub
				setSpeed();
			}
		});

		sbSetDir.setMax(dirRange);
		sbSetDir.setProgress(dirZero);
		sbSetDir.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			@Override
			public void onStopTrackingTouch(SeekBar arg0) {
				// TODO Auto-generated method stub
				if(isBack2Zero)
					sbSetDir.setProgress(dirZero);
			}

			@Override
			public void onStartTrackingTouch(SeekBar arg0) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
				// TODO Auto-generated method stub
				setDir();
			}
		});
	}


	Coding sendData = new Coding();
	public void setSpeed(){
		setCenter = sbSetSpeed.getProgress()-speedZero;
		tvSetSpeed.setText("SetSpeed:\n"+ setCenter);
		myclientService.SendCMD(sendData.control(setCenter * 2,setDir * 2));
	}

	public void setDir(){
		setDir = sbSetDir.getProgress() - dirZero;
		tvSetDir.setText("SetDir:" + setDir);
		myclientService.SendCMD(sendData.control(setCenter * 2,setDir * 2));
	}


	Decode receiveData = new Decode();

	public void initUI()
	{
		mBtnControl.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if( bConnected == false )
				{
					String strIp = edServerIP.getText().toString();
					int nPort = 12345;
					myclientService.ConnectToServer(strIp, nPort, new ControlClientService.ConnectCallback()
					{
						@Override
						public void ConnectCallback(boolean bRet) {
							// TODO Auto-generated method stub
							if(bRet == true)
							{
								mBtnControl.setText(R.string.control_client_disconnect);
								bConnected = true;
							}
							else
							{
								bConnected = false;
								mBtnControl.setText(R.string.control_client_connect);
							}
						}

						@Override
						public void DisconnectCallback() {
							// TODO Auto-generated method stub
							bConnected = false;
							mBtnControl.setText(R.string.control_client_connect);
						}


						@Override
						public void ReceiveCallback(byte[] data) {
							// TODO Auto-generated method stub
							tvReceiveShow.setText("接收数据： "+Arrays.toString(data));
							receiveData.byteArray2num(data);
							showData(data);
						}

					});
				}
				else
				{
					mBtnControl.setText(R.string.control_client_disconnect);
					myclientService.StopClientWork();
				}

			}});
	}


	public void StartService()
	{
		Intent bindingIntent = new Intent(this, ControlClientService.class);
		startService(bindingIntent);
		bindService(bindingIntent, clientConnection, Context.BIND_AUTO_CREATE);
	}

	public void StopService()
	{
		this.unbindService(clientConnection);
		Intent bindingIntent = new Intent(ClientAct.this, ControlClientService.class);
		ClientAct.this.stopService(bindingIntent);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		try{
			StopService();
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}

	private final ServiceConnection clientConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			Log.i(App.MYTAG, "onServiceDisconnected");
			myclientService = ((ControlClientService.ClientServiceBinder) service).getService();
			mBtnControl.setEnabled(true);
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
		}
	};

	UWBDataProcess uwb = new UWBDataProcess(5);
	void showData(byte[] data) {
		MyFormat mFormat = new MyFormat();

		switch (data[0]) {
			case 0x01:
				tvSpeedShow.setText("速度"+"\nLeft: "+mFormat.singleString(receiveData.speed[0])
						                    +"\nRight:"+mFormat.singleString(receiveData.speed[1]));
				break;
			case 0x03:
				uwb.putDistance(receiveData.uwbID,receiveData.uwb);
				uwb.putDistance(receiveData.uwbID2,receiveData.uwbDistance2);
				tvUWBShow.setText("UWB\n"+mFormat.arrayString("UWB",uwb.distance));
				break;
			case 0x04:
			case 0x05:
				tvIRDShow.setText("红外传感器\n"+mFormat.arrayString("IRD",receiveData.ird));
				break;
			case 0x06:
			case 0x07:
			case 0x09:
			case 0x0d:
				tvStatusShow.setText("状态量\n"
						+mFormat.arrayString("防跌落",receiveData.drop)
						+mFormat.arrayString("托盘重量",receiveData.plate)
						+"\n电池电量:"+mFormat.singleString(receiveData.batterySurplus)
						+"\n电池电压:"+mFormat.singleString(receiveData.batteryVoltage)
						+"\n充电状态:"+receiveData.chargeStatus);
				break;
			case 0x0b:
				tvSenersShow.setText("其他传感器\n"+mFormat.arrayString("IMU",receiveData.imu));
			default:
		}
	}
}
